using System;
using System.Collections.Generic;
using UnityEngine;

namespace LFramework
{
    public class GameObjectPool : IDisposable
    {
        private Dictionary<string, GameObjectPoolEntity> PathPoolEntityDic = new Dictionary<string, GameObjectPoolEntity>();
        private Dictionary<int, GameObjectPoolEntity> m_InstanceIDPoolEntityDic = new Dictionary<int, GameObjectPoolEntity>();

        /// <summary>
        /// 出池子
        /// </summary>
        /// <param name="namePath"></param>
        /// <param name="instanceComplete"></param>
        public GameObject Spawn(string assetFullPath, Transform parent)
        {
            GameObjectPoolEntity poolEntity = null;
            if (!PathPoolEntityDic.TryGetValue(assetFullPath, out poolEntity))
            {
                poolEntity = new GameObjectPoolEntity();
                PathPoolEntityDic[assetFullPath] = poolEntity;
            }

            GameObject obj = poolEntity.DeSpawn(assetFullPath, parent);
            m_InstanceIDPoolEntityDic[obj.GetInstanceID()] = poolEntity;
            return obj;
        }

        /// <summary>
        /// 回池
        /// </summary>
        /// <param name="namePath"></param>
        /// <param name="instanceComplete"></param>
        public void Enspawn(GameObject obj)
        {
            if (obj == null)
                return;

            int instanceId = obj.GetInstanceID();
            if (m_InstanceIDPoolEntityDic.TryGetValue(instanceId, out GameObjectPoolEntity poolEntity))
            {
                poolEntity.Enspawn(obj);
                m_InstanceIDPoolEntityDic.Remove(instanceId);
            }
            else
            {
                GameEntry.Log("回池：对象池子不存在", obj.name);
                GameObject.Destroy(obj);
            }
        }

        /// <summary>
        /// 释放对象池
        /// </summary>
        /// <param name="assetFullPath"></param>
        public void ReleasePool(string assetFullPath)
        {
            GameObjectPoolEntity poolEntity = null;
            if (!PathPoolEntityDic.TryGetValue(assetFullPath, out poolEntity))
                return;
            poolEntity.Release();
            PathPoolEntityDic.Remove(assetFullPath);
        }

        public void Dispose()
        {
            PathPoolEntityDic.Clear();
            PathPoolEntityDic = null;
            m_InstanceIDPoolEntityDic.Clear();
            m_InstanceIDPoolEntityDic = null;
        }
    }
}
